<?php
session_start();
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/includes/functions.php';

// 检查用户登录状态
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

// 检查是否有充值记录ID
if (!isset($_GET['deposit_id']) || empty($_GET['deposit_id'])) {
    header('Location: index.php');
    exit;
}

// 获取返回页面参数
$return_url = $_GET['return'] ?? 'index.php';

$deposit_id = intval($_GET['deposit_id']);
$user_id = $_SESSION['user_id'];

// 获取充值记录
try {
    $stmt = $pdo->prepare("
        SELECT dr.*, u.username 
        FROM deposit_records dr 
        JOIN users u ON dr.user_id = u.id 
        WHERE dr.id = ? AND dr.user_id = ? AND dr.status = 'pending'
    ");
    $stmt->execute([$deposit_id, $user_id]);
    $deposit = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$deposit) {
        header('Location: index.php');
        exit;
    }
} catch (PDOException $e) {
    error_log("获取充值记录失败: " . $e->getMessage());
    header('Location: index.php');
    exit;
}

// 支付方式配置
$payment_configs = [
    'alipay' => [
        'name' => '支付宝',
        'qr_code' => 'static/img/alipay_qr.png', // 需要放置支付宝收款码
        'account' => '示例账号@alipay.com',
        'color' => '#1677FF'
    ],
    'wechat' => [
        'name' => '微信支付',
        'qr_code' => 'static/img/wechat_qr.png', // 需要放置微信收款码
        'account' => '微信号：example123',
        'color' => '#07C160'
    ],
    'bank' => [
        'name' => '银行转账',
        'qr_code' => null,
        'account' => '招商银行 6225 8888 1234 5678 (张三)',
        'color' => '#FF6B35'
    ]
];

$payment_config = $payment_configs[$deposit['payment_method']] ?? $payment_configs['alipay'];
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>充值支付 - 投注游戏</title>
    <link rel="icon" href="static/img/logo.png" sizes="32x32" type="image/png">
    <link rel="stylesheet" href="assets/css/mobile.css">
    <style>
        .payment-container {
            min-height: 100vh;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 20px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        
        .payment-card {
            background: white;
            border-radius: 20px;
            padding: 30px;
            margin: 20px 0;
            width: 100%;
            max-width: 400px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            text-align: center;
        }
        
        .payment-header {
            margin-bottom: 25px;
        }
        
        .payment-title {
            font-size: 24px;
            font-weight: bold;
            color: #333;
            margin-bottom: 10px;
        }
        
        .payment-method {
            display: inline-block;
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: bold;
            color: white;
            margin-bottom: 15px;
        }
        
        .amount-display {
            font-size: 36px;
            font-weight: bold;
            color: #e91e63;
            margin: 20px 0;
        }
        
        .random-code-section {
            background: #f8f9fa;
            border-radius: 15px;
            padding: 20px;
            margin: 20px 0;
            border: 2px dashed #667eea;
        }
        
        .random-code-title {
            font-size: 16px;
            font-weight: bold;
            color: #333;
            margin-bottom: 10px;
        }
        
        .random-code {
            font-size: 32px;
            font-weight: bold;
            color: #667eea;
            font-family: 'Courier New', monospace;
            letter-spacing: 4px;
            margin: 15px 0;
        }
        
        .code-notice {
            font-size: 14px;
            color: #f44336;
            font-weight: bold;
        }
        
        .qr-section {
            margin: 25px 0;
        }
        
        .qr-code {
            width: 200px;
            height: 200px;
            border: 3px solid #e0e0e0;
            border-radius: 15px;
            margin: 15px auto;
            display: block;
        }
        
        .account-info {
            background: #f5f5f5;
            border-radius: 10px;
            padding: 15px;
            margin: 15px 0;
            font-size: 14px;
            color: #666;
        }
        
        .payment-steps {
            text-align: left;
            margin: 20px 0;
        }
        
        .step {
            display: flex;
            align-items: center;
            margin: 10px 0;
            font-size: 14px;
            color: #666;
        }
        
        .step-number {
            background: #667eea;
            color: white;
            width: 24px;
            height: 24px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin-right: 12px;
            font-size: 12px;
        }
        
        .action-buttons {
            margin-top: 30px;
            display: flex;
            gap: 15px;
        }
        
        .btn {
            flex: 1;
            padding: 15px;
            border: none;
            border-radius: 10px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .btn-primary {
            background: #667eea;
            color: white;
        }
        
        .btn-primary:hover {
            background: #5a6fd8;
            transform: translateY(-2px);
        }
        
        .btn-secondary {
            background: #f5f5f5;
            color: #666;
        }
        
        .btn-secondary:hover {
            background: #e0e0e0;
        }
        
        .countdown {
            font-size: 14px;
            color: #f44336;
            margin-top: 15px;
        }
        
        .warning-text {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 8px;
            padding: 12px;
            margin: 15px 0;
            font-size: 13px;
            color: #856404;
        }
    </style>
</head>
<body>
    <div class="payment-container">
        <!-- 支付信息卡片 -->
        <div class="payment-card">
            <div class="payment-header">
                <div class="payment-title">确认支付</div>
                <div class="payment-method" style="background-color: <?php echo $payment_config['color']; ?>">
                    <?php echo $payment_config['name']; ?>
                </div>
            </div>
            
            <div class="amount-display">¥<?php echo number_format($deposit['amount'], 2); ?></div>
            
            <!-- 随机码显示 -->
            <div class="random-code-section">
                <div class="random-code-title">🔢 付款备注码</div>
                <div class="random-code"><?php echo $deposit['random_code']; ?></div>
                <div class="code-notice">⚠️ 转账时请务必填写此备注码</div>
            </div>
            
            <!-- 支付二维码或账户信息 -->
            <?php if ($payment_config['qr_code'] && file_exists($payment_config['qr_code'])): ?>
            <div class="qr-section">
                <h4>扫码支付</h4>
                <img src="<?php echo $payment_config['qr_code']; ?>" alt="支付二维码" class="qr-code">
            </div>
            <?php endif; ?>
            
            <div class="account-info">
                <strong>收款账户：</strong><br>
                <?php echo $payment_config['account']; ?>
            </div>
            
            <!-- 支付步骤 -->
            <div class="payment-steps">
                <div class="step">
                    <div class="step-number">1</div>
                    <div>打开<?php echo $payment_config['name']; ?>APP</div>
                </div>
                <div class="step">
                    <div class="step-number">2</div>
                    <div>扫描上方二维码或转账到指定账户</div>
                </div>
                <div class="step">
                    <div class="step-number">3</div>
                    <div><strong>在备注中填写：<?php echo $deposit['random_code']; ?></strong></div>
                </div>
                <div class="step">
                    <div class="step-number">4</div>
                    <div>完成支付并等待到账确认</div>
                </div>
            </div>
            
            <div class="warning-text">
                <strong>重要提醒：</strong><br>
                • 转账时必须填写备注码，否则无法自动到账<br>
                • 请在30分钟内完成支付<br>
                • 支付完成后请保留支付凭证
            </div>
            
            <div class="countdown" id="countdown">
                ⏱️ 支付剩余时间：<span id="time">30:00</span>
            </div>
            
            <div class="action-buttons">
                <button class="btn btn-secondary" onclick="cancelPayment()">取消支付</button>
                <button class="btn btn-primary" onclick="checkPaymentStatus()">我已支付</button>
            </div>
        </div>
        
        <!-- 支付说明卡片 -->
        <div class="payment-card">
            <h4>📋 支付说明</h4>
            <div style="text-align: left; font-size: 14px; color: #666; line-height: 1.6;">
                <p>• <strong>备注码必填：</strong>转账时请务必在备注中填写上方显示的4位数字码</p>
                <p>• <strong>金额准确：</strong>请确保转账金额与显示金额完全一致</p>
                <p>• <strong>到账时间：</strong>正常情况下5-10分钟内到账</p>
                <p>• <strong>客服支持：</strong>如有问题请联系在线客服</p>
            </div>
        </div>
    </div>

    <script>
        // 30分钟倒计时
        let timeLeft = 30 * 60; // 30分钟
        
        function updateCountdown() {
            const minutes = Math.floor(timeLeft / 60);
            const seconds = timeLeft % 60;
            document.getElementById('time').textContent = 
                `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
            
            if (timeLeft <= 0) {
                alert('支付超时，请重新发起充值');
                // 跳转回原始页面
                window.location.href = '<?php echo htmlspecialchars($return_url); ?>';
                return;
            }
            
            timeLeft--;
        }
        
        // 每秒更新倒计时
        setInterval(updateCountdown, 1000);
        updateCountdown();
        
        // 取消支付
        function cancelPayment() {
            if (confirm('确定要取消支付吗？')) {
                // 更新充值记录状态为已取消
                fetch('./ajax/cancel_deposit.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        deposit_id: <?php echo $deposit_id; ?>
                    })
                })
                .catch(error => {
                    console.error('取消支付失败:', error);
                });
                // 跳转回原始页面
                window.location.href = '<?php echo htmlspecialchars($return_url); ?>';
            }
        }
        
        // 检查支付状态
        function checkPaymentStatus() {
            fetch('./ajax/check_deposit_status.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    deposit_id: <?php echo $deposit_id; ?>
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    if (data.status === 'completed') {
                        alert('充值成功！正在返回...');
                        // 跳转回原始页面
                        window.location.href = '<?php echo htmlspecialchars($return_url); ?>';
                    } else {
                        alert('支付确认中，请稍候...\n如已完成支付请耐心等待人工确认');
                        
                    }
                } else {
                    alert('检查失败：' + data.message);
                }
            })
            .catch(error => {
                console.error('检查支付状态失败:', error);
                alert('网络错误，请重试');
            });
        }
        
        // 定期检查支付状态（每30秒）
        setInterval(() => {
            fetch('./ajax/check_deposit_status.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    deposit_id: <?php echo $deposit_id; ?>
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success && data.status === 'completed') {
                    alert('充值成功！余额已到账，正在返回...');
                    window.location.href = '<?php echo htmlspecialchars($return_url); ?>';
                }
            })
            .catch(error => {
                console.error('自动检查支付状态失败:', error);
                // 错误不需要向用户显示
            });
        }, 30000); // 30秒检查一次
    </script>
</body>
</html>
